package admin.models;

import helpers.GeneralHelper;

import java.util.ArrayList;
import java.util.List;

import javax.cache.Cache;

import com.google.appengine.api.NamespaceManager;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;

import entities.ApplicationTemplate;

public class ApplicationTemplateModel {
	private Objectify ofy;
	
	private Cache cache = null;
	
	private String cachePrefix = "application_template_";
	
	private static ApplicationTemplateModel instance = null;
	
	public static ApplicationTemplateModel getInstance() {
		if (instance == null) {
			instance = new ApplicationTemplateModel();
		}
		
		return instance;
	}
	
	private ApplicationTemplateModel() {
		try {
			ObjectifyService.register(ApplicationTemplate.class);
		} catch (Exception e) {
			//e.printStackTrace();
		}
		
		cache = GeneralHelper.getCache();
		ofy = GeneralHelper.getObjectify();
	}
	
	public List<ApplicationTemplate> list(int page, int limit) {
		
		List<ApplicationTemplate> templates = new ArrayList<ApplicationTemplate>();
		
		String cacheName = cachePrefix + "list_page_" + page + "_limit_" + limit;
		boolean isCached = false;
		
		/*if (cache != null) {
			try {
				templates = (List<Template>) cache.get(cacheName);
				if (templates != null) isCached = true;
			} catch (Exception e) {
				// TODO: handle exception
			}
		}*/
		
		if (!isCached) {
			int start = (page - 1) * limit;
			templates = ofy.query(ApplicationTemplate.class).limit(limit).offset(start).list();
			
			/*if (cache != null && templates != null) {
				try {
					cache.put(cacheName, templates);
				} catch (Exception e) {
					// TODO: handle exception
				}
			}*/
		}
		
		return templates;
	}
	
	public List<ApplicationTemplate> listAll() {
		List<ApplicationTemplate> templates = new ArrayList<ApplicationTemplate>();
		
		templates = ofy.query(ApplicationTemplate.class).list();
		
		if (templates == null) {
			templates = new ArrayList<ApplicationTemplate>();
		}
		
		return templates;
	}
	
	public void insert(ApplicationTemplate appTemplate) {
		ofy.put(appTemplate);
		
	}
	
	public void delete(ApplicationTemplate appTemplate) {
		
		ofy.delete(appTemplate);
		
	}
	
	public ApplicationTemplate get(String id) {
		
		ApplicationTemplate appTemplate = new ApplicationTemplate();
		
		try {
			appTemplate = ofy.get(new Key<ApplicationTemplate>(ApplicationTemplate.class, id));
		} catch (Exception e) {
			appTemplate = null;
		}
		
		return appTemplate;
	}
}
